package com.youxue.teachin.webplugin;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.google.gson.Gson;
import com.hybrid.utils.UriParams;
import com.hybrid.webview.MenuItem;
import com.hybrid.webview.ParamBuilder;
import com.hybrid.webview.WVWebView;
import com.hybrid.webview.WVWebView.Callback;
import com.library.uiframework.activity.ActionBarLayoutActivity;
import com.library.uiframework.fragment.ptr.PtrViewHelper.OnPtrHandlerListener;
import com.library.uiframework.utils.ListUtils;
import com.library.uiframework.utils.Log;
import com.library.uiframework.utils.StringUtils;
import com.library.uiframework.widget.actionbar.ActionBarLayout.Action;
import com.library.uiframework.widget.actionbar.ActionMenuItem;
import com.youxue.teachin.R;
import com.youxue.teachin.common.utils.SchemaParam;
import com.youxue.teachin.webplugin.JavaScriptObject.JavaScriptListener;
import com.youxue.teachin.youmen.UMenUtils;
import com.youxue.teachin.youmen.UmenEventId;
import com.youxue.teachin.youmen.UmenEventId.EventMap;
import in.srain.cube.views.ptr.PtrClassicFrameLayout;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.PtrFrameLayout.Mode;
import in.srain.cube.views.ptr.PtrHandler;
import org.json.JSONException;
import org.json.JSONObject;

import static com.library.uiframework.slidingclose.SlidingClosableRelativeLayout.SLIDING_CLOSE_MODE_NONE;
import static com.youxue.teachin.common.utils.SchemaParam.PARAM_WEBVIEW;

/**
 * 在此写用途
 *
 * @author: zhiwei
 * @date: 2017-10-10 20:57
 * @version: 9.1.0
 */
public class BaseWebActionbarActivity extends ActionBarLayoutActivity implements OnPtrHandlerListener,
    JavaScriptListener {
    private static final String ORIGIN_DEFAULT_TITLE = "";
    private final String TAG = this.getClass().getSimpleName();

    protected WVWebView mWebView;
    protected PtrClassicFrameLayout mPtrFrameLayout;
    private WebViewParam mWebViewParam = new WebViewParam();
    protected String mCurrentUrl;
    private String mWebPageName;

    private List<ActionMenuItem> mMenuItemList = new ArrayList<ActionMenuItem>();
    private Map<ActionMenuItem, MenuItem> mMenuItemMap = new LinkedHashMap<ActionMenuItem, MenuItem>();
    private List<Menu> mRightMenuList;

    @Override
    protected void setBusinessView(View businessView) {
        super.setBusinessView(businessView);
        initWebParamFromArguments();
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        //getActionBarLayout().setFloatingModeAlpha(0);
        //getActionBarLayout().getTitleView().setAlpha(1);
        //setTitleColor(getResources().getColor(R.color.cl_1));
        setSlidingCloseMode(SLIDING_CLOSE_MODE_NONE);
        initView();
        loadWebView();
    }

    @Override
    protected void onCreatePopupMenu(List<ActionMenuItem> menus) {
        super.onCreatePopupMenu(menus);
        menus.addAll(mMenuItemList);
    }

    @Override
    protected boolean onPopupMenuSelected(View view, ActionMenuItem actionMenuItemSelected, int position) {
        // 交予Plugin处理
        for (int index = 0; index < mMenuItemList.size(); index++) {
            ActionMenuItem actionMenuItem = mMenuItemList.get(index);
            if (actionMenuItem == actionMenuItemSelected) {
                MenuItem menuItem = mMenuItemMap.get(actionMenuItem);
                ParamBuilder paramBuilder = new ParamBuilder();
                JSONObject jsonObject = new JSONObject();
                try {
                    String id = menuItem.getId();
                    String name = menuItem.getName();
                    jsonObject.put("id", null != id ? id : "");
                    jsonObject.put("name", null != name ? name : "");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                paramBuilder.addParamJsonObject("menu", jsonObject);
                mWebView.fireEvent(MenuItem.EVENT_MENU_ITEM_CLICK_INVOKE, paramBuilder.buildParamString());
                return false;
            }
        }
        // 交予框架处理
        return super.onPopupMenuSelected(view, actionMenuItemSelected, position);
    }

    @Override
    protected View onCreateContentView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.main_tab_faxian_activity, container, false);
        return view;
    }

    void beginRefresh2H5() {
        if (mWebViewParam.mNotificationPtrRefresh) {
            String beginRefreshing = "javascript:beginRefreshing()";
            mWebView.evaluateJavascript(beginRefreshing);
        } else {
            mWebView.refresh();
        }
    }

    private void initWebParamFromArguments() {
        Bundle arguments = getIntent().getExtras();
        if (null != arguments) {
            Serializable serializableParam = arguments.getSerializable(PARAM_WEBVIEW);
            if (null == serializableParam) {
                mWebViewParam.mUrl = arguments.getString(SchemaParam.URL);
                if (StringUtils.isNotEmpty(mWebViewParam.mUrl)) {
                    //Uri webViewUri = Uri.parse(mWebViewParam.mUrl);
                    //mWebViewParam.mNeedRefresh = "1".equals(webViewUri.getQueryParameter(SchemaParam.H5_NEED_REFRESH));
                    //mWebViewParam.mHideActionBar = "1".equals(
                    //    webViewUri.getQueryParameter(SchemaParam.H5_IDE_ACTION_BAR));
                    //mWebViewParam.mNeedActionBack = "1".equals(
                    //    webViewUri.getQueryParameter(SchemaParam.H5_NEED_BACK));
                    //mWebViewParam.mTitle = webViewUri.getQueryParameter(SchemaParam.TITLE);
                    //if (StringUtils.isNotEmpty(mWebViewParam.mTitle)) {
                    //    mWebViewParam.mTitleLock = true;
                    //    updateTitle(mWebViewParam.mTitle);
                    //}
                    UriParams uriParams = UriParams.from(mWebViewParam.mUrl);
                    mWebViewParam.mNeedRefresh = uriParams.getBoolean(SchemaParam.H5_NEED_REFRESH, true);
                    mWebViewParam.mNeedActionBack = uriParams.getBoolean(SchemaParam.H5_NEED_BACK, true);
                    mWebViewParam.mNotificationPtrRefresh = uriParams.getBoolean(SchemaParam.H5_INFORM_REFRESH, true);
                    mWebViewParam.mHideActionBar = uriParams.getBoolean(SchemaParam.H5_IDE_ACTION_BAR, false);
                    mWebViewParam.mTitle = uriParams.getString(SchemaParam.TITLE, null);
                    if (StringUtils.isNotEmpty(mWebViewParam.mTitle)) {
                        mWebViewParam.mTitleLock = true;
                        updateTitle(mWebViewParam.mTitle);
                    }
                }
            } else {
                mWebViewParam = (WebViewParam)serializableParam;
            }

            // 移除Serializable参数,防止Activity在onStop之后对Bundle数据进行Restore进行writeObject,产生NotSerializableException
            arguments.remove(PARAM_WEBVIEW);
        }
    }

    private void initView() {
        mWebView = (WVWebView)findViewById(R.id.webview);
        mWebView.addJavascriptInterface(new JavaScriptObject(mWebView, this), "WebViewFunc");
        mWebView.actionSetCallback(new Callback() {
            @Override
            public void onReceivedTitle(String title) {
                updateTitle(title);
                mWebPageName = "web_" + title;
            }

            @Override
            public void onPageStarted(String url) {
                //beginLoading();

            }

            @Override
            public void onPageFinished(String url) {
                //endLoading();
                mPtrFrameLayout.refreshComplete();
                UMenUtils.onEvent(UmenEventId.EVENT_WEB_OPEN,
                    new EventMap()
                        .add("name", mWebPageName)
                        .add("url", url)
                        .buile());
            }

            @Override
            public void onProgressChanged(int progress) {
                //progressLoading(progress);
            }

            @Override
            public void onReceivedError(WebView view, String failingUrl) {
                UMenUtils.onEvent(UmenEventId.EVENT_WEB_OPEN_ERROR,
                    new EventMap()
                        .add("url", failingUrl)
                        .buile());
                //android.util.Log.e("致伟",
                //    this.getClass().getSimpleName() + " onReceivedError: failingUrl=" + failingUrl);
                //TextView info = (TextView) mLoadFailedView.findViewById(R.id.textview_load_failed);
                //info.setText(
                //    NetworkUtils.isNetworkAvailable(mLoadFailedView.getContext()) ? R.string.load_comment_fail : R
                // .string.load_failed_no_network);
                //mLoadFailedView.setVisibility(View.VISIBLE);
            }
        });

        mWebView.setAdvancedCallback(new WVWebView.IWebAdvancedCallback() {
            @Override
            public void onPageClose() {
                finish();
            }

            @Override
            public void onUpdateMenu(List<MenuItem> menuItemList) {
                updateMenuInner(menuItemList);
            }

            @Override
            public void onUpdateTitle(String title) {
                updateTitleFromCallback(title);
            }

            @Override
            public void onUpdateStatusBarAlpha(float alpha) {
                updateStatusBarAlpha(alpha);
            }
        });

        mPtrFrameLayout = (PtrClassicFrameLayout)findViewById(R.id.ptr_frame_layout);
        mPtrFrameLayout.setMode(Mode.REFRESH);
        mPtrFrameLayout.disableWhenHorizontalMove(true);
        mPtrFrameLayout.setPtrHandler(new PtrHandler() {
            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                return mWebViewParam.mNeedRefresh && mWebView.getScrollY() <= 0;
            }

            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                //mWebView.refresh();
                beginRefresh2H5();
            }
        });
    }

    /********************************************************************************
     * 私有方法
     ********************************************************************************/
    private void updateMenuInner(List<MenuItem> menuItemList) {
        mMenuItemList.clear();
        mMenuItemMap.clear();
        if (null != menuItemList) {
            for (int index = 0; index < menuItemList.size(); index++) {
                MenuItem menuItem = menuItemList.get(index);
                ActionMenuItem actionMenuItem = new ActionMenuItem(MenuItem.MENU_ITEM_ID_INDEX + index,
                    menuItem.getName());
                mMenuItemList.add(actionMenuItem);
                mMenuItemMap.put(actionMenuItem, menuItem);
            }
        }
    }

    private void updateStatusBarAlpha(float alpha) {
        setFloatingMode(true);
        getActionBarLayout().setFloatingModeAlpha(alpha);
    }

    private void updateTitle(String title) {
        // 设置固定标题
        if (null != mWebViewParam.mTitle && mWebViewParam.mTitleLock) {
            Log.v(TAG, "WebViewFragment updateTitle 固定设置 (title) = " + mWebViewParam.mTitle);
            setTitle(mWebViewParam.mTitle);
        }
        // 设置动态标题
        else {
            if (null != title) {
                Log.v(TAG, "WebViewFragment updateTitle 动态设置 (title) = " + title);
                setTitle(title);
            } else if (null != mWebViewParam.mTitle) {
                Log.v(TAG, "WebViewFragment updateTitle 用户默认 (title) = " + mWebViewParam.mTitle);
                setTitle(mWebViewParam.mTitle);
            } else {
                Log.v(TAG, "WebViewFragment updateTitle 原生默认 (title) = " + ORIGIN_DEFAULT_TITLE);
                setTitle(ORIGIN_DEFAULT_TITLE);
            }
        }
    }

    private void updateTitleFromCallback(String title) {
        Log.v(TAG, "WebViewFragment updateTitleFromCallback (title) = " + title);
        if (null != title) {
            setTitle(title);
        }
    }

    @Override
    protected boolean needBackAction() {
        return mWebViewParam.mNeedActionBack;
    }

    @Override
    protected boolean needMenuAction() {
        return mWebViewParam.mNeedMenu;
    }

    protected void loadWebView() {
        if (!TextUtils.isEmpty(mWebViewParam.mUrl)) {
            load(mWebViewParam.mUrl);
        }
    }

    public void load(String url) {
        mCurrentUrl = url;
        mWebView.loadUrl(url);
    }

    @Override
    public void onLoadMoreBegin(PtrFrameLayout frameLayout) {

    }

    @Override
    public void onRefreshBegin(PtrFrameLayout frameLayout) {
        //mWebView.refresh();
        beginRefresh2H5();
    }

    @Override
    public boolean onInterceptLoadMore() {
        return true;
    }

    @Override
    public boolean onInterceptRefresh() {
        if (!mWebViewParam.mNeedRefresh) {
            return true;
        }
        return mWebViewParam.mNeedRefresh && !(mWebView.getScrollY() == 0);
    }

    @Override
    public void endRefreshing() {
        mWebView.post(new Runnable() {
            @Override
            public void run() {
                mWebView.stopLoading();
                mPtrFrameLayout.refreshComplete();
            }
        });
    }

    @Override
    public void beginRefreshing() {
        mWebView.post(new Runnable() {
            @Override
            public void run() {
                mPtrFrameLayout.autoRefresh();
                mWebView.refresh();
            }
        });
    }

    private Menu getMenu(int menuId) {
        Menu retMenu = null;
        for (Menu menu : mRightMenuList) {
            if (menuId == menu.id) {
                retMenu = menu;
                break;
            }
        }
        return retMenu;
    }

    @Override
    protected Action createBack() {
        return addLeftImageAction(ACTION_BACK, R.drawable.top_return);
    }

    @Override
    protected void onActionClick(int actionId, Action action) {
        super.onActionClick(actionId, action);
        if (ListUtils.isNotEmpty(mMenuItemList)) {
            ParamBuilder paramBuilder = new ParamBuilder();
            JSONObject jsonObject = new JSONObject();
            Menu menu = getMenu(actionId);
            if (menu == null) {
                return;
            }
            try {
                int id = menu.id;
                String name = menu.name;
                jsonObject.put("id", id);
                jsonObject.put("name", null != name ? name : "");
            } catch (JSONException e) {
                e.printStackTrace();
            }
            paramBuilder.addParamJsonObject("menu", jsonObject);
            android.util.Log.e("致伟",
                this.getClass().getSimpleName() + " onActionClick: =" + paramBuilder.buildParamString());

            mWebView.fireEvent(MenuItem.EVENT_MENU_ITEM_CLICK_INVOKE, paramBuilder.buildParamString());
        }
    }

    @Override
    public void setRefreshState(int state) {
        if (state == 1) {
            mWebViewParam.mNeedRefresh = true;
        } else {
            mWebViewParam.mNeedRefresh = false;
        }
    }

    @Override
    public void updateMenu(final String string) {
        if (StringUtils.isEmpty(string)) {
            return;
        }
        mWebView.post(new Runnable() {
            @Override
            public void run() {
                try {
                    Gson gson = new Gson();
                    Menus menus = gson.fromJson(string, Menus.class);
                    if (ListUtils.isEmpty(menus.rightMenus)) {
                        return;
                    }
                    int maxRightMenus = Menus.MAX_MENUS;
                    List<Menu> menuList = ListUtils.removeItem(menus.rightMenus, maxRightMenus,
                        menus.rightMenus.size() - maxRightMenus);
                    for (Menu rightMenu : menuList) {
                        if (StringUtils.isNotEmpty(rightMenu.icon)) {
                            final Menu tempMenu = rightMenu;
                            Glide.with(BaseWebActionbarActivity.this)
                                .load(rightMenu.icon)
                                .into(new SimpleTarget<GlideDrawable>() {
                                    @Override
                                    public void onResourceReady(GlideDrawable resource,
                                                                GlideAnimation<? super GlideDrawable> glideAnimation) {
                                        Action action = getActionBarLayout().addImageAction(
                                            MenuItem.MENU_ITEM_ID_INDEX + tempMenu.id, resource);
                                        action.setOnActionClickListener(getOnActionClickListener());
                                    }
                                });
                        } else if (StringUtils.isNotEmpty(rightMenu.name)) {
                            Action action = getActionBarLayout().addTextAction(
                                MenuItem.MENU_ITEM_ID_INDEX + rightMenu.id,
                                rightMenu.name);
                            action.setOnActionClickListener(getOnActionClickListener());
                        }
                    }
                } catch (Throwable throwable) {

                }
            }
        });
    }
}
